#include "auto_feed.h"

#if (COMPLIE_AUTO_FEED == 1)

void servo_port_listen(e_cc_port src_id, e_cc_port dst_id, const char *topic, void* msg)
{
  cc_log("port(%d) recv from port(%d) topic(%s)\r\n", dst_id, src_id, topic);
  user_device_t servo = cc_device_get(devices, CC_DEVICE_TYPE_SERVO, 1);
  user_device_t scale = cc_device_get(devices, CC_DEVICE_TYPE_SCALE, 1);
  if (servo == CC_NULL || scale == CC_NULL)
  {
    cc_log("device is null\r\n");
  }
  if (strcmp(topic, "servo_ctrl") == 0)
  {
    if (strcmp("servo_open", (char *)msg) == 0)
    {
      // TEST add weight
      // scale->num_data[0] += 10;
      float weight;
      scale->read_cb(scale, CC_NULL, CC_SCALE_READ_GRAM, &weight);
      if (weight < setting_weight)
      {
        servo->control_cb(servo, CC_NULL, CC_SERVO_OPEN, CC_NULL);

#if (CC_CONFIG_USE_MQTT && CC_CONFIG_USE_WIFI)
        cc_msg_mqtt_publish("cc_msg_resp", "open servo");
#endif
        return;
      }
      else
      {
        cc_log_e("weight is bigger,can't open\r\n");
      }
    }
    else if (strcmp("servo_close", (char *)msg) == 0)
    {
      servo->control_cb(servo, CC_NULL, CC_SERVO_STOP, CC_NULL);
      cc_log("close servo\r\n");
#if (CC_CONFIG_USE_MQTT && CC_CONFIG_USE_WIFI)
      cc_msg_mqtt_publish("cc_msg_resp", "close servo");
#endif
    }
    else
    {
      cc_log_e("unknow msg\r\n");
    }
  }
  return;
}

void servo_device_thread(void *param)
{
  cc_port_t servo_port = cc_port_init(CC_PORT_AUTO_FEED_SERVO, "feed_servo", 10, 50);
  cc_port_listen(servo_port, servo_port_listen);
  cc_port_subsribe(servo_port, "servo_ctrl");
  cc_port_set_state(servo_port, CC_PORT_STATE_CONN);

  while (1)
  {
    cc_delay(2000);
  }
}
CC_THREAD_REGISTER(servo_device_thread, 10, 2048);



#if (CC_CONFIG_USE_MQTT && CC_CONFIG_USE_WIFI)
// mqtt回调部分
void auto_feed_mqtt_cb(char *topic, char *msg, int length, int topic_len)
{
  cc_port_t mqtt_port = cc_port_init(CC_PORT_AUTO_FEED_MQTT, "feed_mqtt", 10, 50);
  cc_port_set_state(mqtt_port, CC_PORT_STATE_CONN);
  cc_mnode_t node = CC_NULL;
  if (strcmp(msg, "servo_open") == 0 || strcmp(msg, "servo_close") == 0)
  {
    node = cc_port_get_msg_node(mqtt_port, 1000);
    sprintf((char *)node->mem, msg);
    cc_port_publish(mqtt_port, "servo_ctrl", node);
  }
}
CC_TOPIC_SUBSRIBE_ALIAS(auto_feed_mqtt_cb, "cc_feed_mqtt")
#endif

#endif